import Log4R from "../log/Log4R"

interface PreLoadedAnimEntity {
    name?: string
    animation?: Animation
}
const loginfo = Log4R.getLog('all')
const logError = Log4R.getLog('error')

export const loadedAnims: {
    [key: string]: PreLoadedAnimEntity
} = {}
const ContentProvider = game.GetService('ContentProvider')
const loadFunc = (anim: Animation, retry = 0) => {
    if (retry > 3) {
        logError?.error('load anim failue', anim.AnimationId)
        return
    }
    ContentProvider.PreloadAsync([anim], (contentid, ass) => {
        if (ass === Enum.AssetFetchStatus.Failure) {
            task.delay(1, () => {
                loadFunc(anim, retry++)
            })
        }
    });
}
export function getLoadedAnim(id: string) {
    if (loadedAnims[id]?.animation) {
        // loginfo?.info('<-----------------get Cache', id)
        return loadedAnims[id].animation as Animation
    } else {
        const newAnimation = new Instance('Animation');
        newAnimation.AnimationId = id
        loadedAnims[id] = {
            animation: newAnimation
        }
        task.spawn(() => {
            loadFunc(newAnimation)
        })
        return loadedAnims[id].animation as Animation
    }
}
export function getLoadedAnimEntity(id: string) {
    return loadedAnims[id]
}
export function preLoadAnim(id: string, entity?: PreLoadedAnimEntity) {
    // if (id === 'rbxassetid://13552618986')
    //     loginfo?.info('preLoadAnim', id)
    if (loadedAnims[id]) {
        return
    }
    const animation = new Instance('Animation');
    animation.AnimationId = id
    task.spawn(() => {
        // loginfo?.info('load', animation)
        loadFunc(animation)
    })
    loadedAnims[id] = {
        ...entity,
        animation
    }
}